﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;

namespace Smart_Archives.Controllers
{
    /// <summary>
    /// 上传文件接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class UploadController : ControllerBase
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public UploadController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
        [HttpPost]
        public JsonResult Post([FromForm] IFormCollection formCollection)
        {

            string result = "";
            //获取站点目录
            string webRootPath = _hostingEnvironment.WebRootPath;
            string contentRootPath = _hostingEnvironment.ContentRootPath;
            //获取表单中文件集合
            FormFileCollection fileList = (FormFileCollection)formCollection.Files;
            var urlList = new List<String>();
            foreach (IFormFile file in fileList)
            {
                var tPath = @"/attach/" + DateTime.Now.ToString("yyyy-MM-dd") + @"/";
                var name = file.FileName;
                var fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                var filePath = webRootPath + tPath;
                //文件拓展类型
                var type = Path.GetExtension(name);
                DirectoryInfo di = new DirectoryInfo(filePath);

                //判断文件是否存在
                if (!di.Exists) { di.Create(); }

                using (FileStream fs = System.IO.File.Create(filePath + fileName + type))
                {
                    // 复制文件
                    file.CopyTo(fs);
                    // 清空缓冲区数据
                    fs.Flush();
                }
                urlList.Add(tPath + fileName + type);

            }

            return new JsonResult(new
            {
                succeed = true,
                url = urlList
            });
        }

        [HttpGet]
        public IActionResult Get(string filepath)
        {
            //如果不为空 使用传过来的参数地址 否则使用测试地址
            if (string.IsNullOrEmpty(filepath))
                filepath = "wwwroot/attach/2019-09-11/anflml.xlsx";
            var provider = new FileExtensionContentTypeProvider();
            //读取文件信息
            FileInfo fileInfo = new FileInfo(filepath);
            //获取拓展名
            var ext = fileInfo.Extension;
            //获取拓展类型
            new FileExtensionContentTypeProvider().Mappings.TryGetValue(ext, out var contentType);
            //根据文件拓展类型返回文件流
            return File(System.IO.File.ReadAllBytes(filepath), contentType ?? "application/octet-stream", fileInfo.Name);
        }

    }
}